package com.cyl.manager.lbs.service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.annotation.JSONField;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cyl.manager.act.mapper.CouponActivityMapper;
import com.cyl.manager.del.service.LbsMgzService;
import com.cyl.manager.lbs.domain.LbsZbjl;
import com.cyl.manager.lbs.mapper.LbsZbjlMapper;
import com.cyl.manager.lbs.pojo.query.LbsZbjlQuery;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Maps;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.livesass.LiveVideoService;
import com.ruoyi.livesass.ProductVideoService;
import com.ruoyi.livesass.api.sync.LiveTrafficDataSynService;
import com.ruoyi.livesass.api.sync.SysConfigUtils;
import com.ruoyi.system.domain.SysConfig;
import com.ruoyi.system.service.ISysConfigService;
import com.volcengine.model.livesaas.response.CommonResponse;
import com.volcengine.model.livesaas.response.CreateActivityAPIResponse;
import com.volcengine.model.livesaas.response.CreateActivityAPIResponse.CommonResp;
import com.volcengine.model.livesaas.response.GetActivityAPIResponse;
import com.volcengine.model.livesaas.response.GetStreamsAPIResponse.ForwardInfoAPI;
import com.volcengine.model.livesaas.response.GetStreamsAPIResponse.GetStreamsAPILineDetail;
import com.volcengine.model.livesaas.response.GetStreamsAPIResponse.PushInfoAPI;
import com.volcengine.model.livesaas.response.ModifyActivityMenusResponse;
import com.volcengine.model.response.ResponseMetadata;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;


/**
 * 直播列表Service业务层处理
 *
 *
 * @author zcc
 */
@Service
public class LbsZbjlService {
	
	private static final Logger LOG = LoggerFactory.getLogger(LiveTrafficDataSynService.class);
	
    @Autowired
    private LbsZbjlMapper lbsZbjlMapper;

    @Autowired
    private LiveVideoService liveVideoService;
    

    @Autowired
    private ProductVideoService productVideoService;
    
    @Autowired
    private CouponActivityMapper couponActivityMapper;
    
    @Autowired
    private LbsMgzService lbsMgzService;
    
    @Autowired
    SysConfigUtils sysConfigUtils;
    
    
    /**
     * 查询直播列表
     *
     * @param id 直播列表主键
     * @return 直播列表
     */
    public LbsZbjl selectById(Long id) {
        return lbsZbjlMapper.selectById(id);
    }

    /**
     * 查询直播列表列表
     *
     * @param query 查询条件
     * @param page 分页条件
     * @return 直播列表
     */
    public List<LbsZbjl> selectList(LbsZbjlQuery query, Pageable page) {
        if (page != null) {
            PageHelper.startPage(page.getPageNumber() + 1, page.getPageSize() , "create_time desc");
        }
        QueryWrapper<LbsZbjl> qw = new QueryWrapper<>();
        qw.eq("del_flag",0);
        Long qrDeptZbjId = query.getDeptZbjId();
        if(qrDeptZbjId!=null) {
            qw.eq("dept_zbj_id", qrDeptZbjId);
        }

        if (!StringUtils.isEmpty(query.getBeginTime()) && !StringUtils.isEmpty(query.getEndTime())){
            qw.ge("create_time", query.getBeginTime());
            qw.lt("create_time", query.getEndTime());
        }
        
        String zbjzt = query.getZbjzt();
        if (!StringUtils.isEmpty(zbjzt)) {
            qw.eq("zbjzt", zbjzt);
        }
        Long zbjbmid = query.getZbjbmid();
        if (zbjbmid != null) {
            qw.eq("zbjbmid", zbjbmid);
        }
        
        Long createBy = query.getCreateBy();
        if (createBy != null) {
            qw.eq("create_by", createBy);
        }
        
        String zbjmc = query.getZbjmc();
        if (!StringUtils.isEmpty(zbjmc)) {
            qw.eq("zbjmc", zbjmc);
        }
        String zbqd = query.getZbqd();
        if (!StringUtils.isEmpty(zbqd)) {
            qw.eq("zbqd", zbqd);
        }
        String kjptlx = query.getKjptlx();
        if (!StringUtils.isEmpty(kjptlx)) {
            qw.eq("kjptlx", kjptlx);
        }
        String zbjlx = query.getZbjlx();
        if (!StringUtils.isEmpty(zbjlx)) {
            qw.eq("zbjlx", zbjlx);
        }
        String hsplx = query.getHsplx();
        if (!StringUtils.isEmpty(hsplx)) {
            qw.eq("hsplx", hsplx);
        }
        String kbfslx = query.getKbfslx();
        if (!StringUtils.isEmpty(kbfslx)) {
            qw.eq("kbfslx", kbfslx);
        }
        String zbqxdlx = query.getZbqxdlx();
        if (!StringUtils.isEmpty(zbqxdlx)) {
            qw.eq("zbqxdlx", zbqxdlx);
        }
        String zbyslx = query.getZbyslx();
        if (!StringUtils.isEmpty(zbyslx)) {
            qw.eq("zbyslx", zbyslx);
        }
        String hpfmt = query.getHpfmt();
        if (!StringUtils.isEmpty(hpfmt)) {
            qw.eq("hpfmt", hpfmt);
        }
        String spfmt = query.getSpfmt();
        if (!StringUtils.isEmpty(spfmt)) {
            qw.eq("spfmt", spfmt);
        }
        String fxt = query.getFxt();
        if (!StringUtils.isEmpty(fxt)) {
            qw.eq("fxt", fxt);
        }
        String jhkssj = query.getJhkssj();
        if (!StringUtils.isEmpty(jhkssj)) {
            qw.eq("jhkssj", jhkssj);
        }
        String jhjssj = query.getJhjssj();
        if (!StringUtils.isEmpty(jhjssj)) {
            qw.eq("jhjssj", jhjssj);
        }
        String zbnc = query.getZbnc();
        if (!StringUtils.isEmpty(zbnc)) {
            qw.eq("zbnc", zbnc);
        }
        String zbwxh = query.getZbwxh();
        if (!StringUtils.isEmpty(zbwxh)) {
            qw.eq("zbwxh", zbwxh);
        }
        String hlqsj = query.getHlqsj();
        if (!StringUtils.isEmpty(hlqsj)) {
            qw.eq("hlqsj", hlqsj);
        }
        Long hlqid = query.getHlqid();
        if (hlqid != null) {
            qw.eq("hlqid", hlqid);
        }
        String zbtldz = query.getZbtldz();
        if (!StringUtils.isEmpty(zbtldz)) {
            qw.eq("zbtldz", zbtldz);
        }
        String zbtlmy = query.getZbtlmy();
        if (!StringUtils.isEmpty(zbtlmy)) {
            qw.eq("zbtlmy", zbtlmy);
        }
        String zbdlmy = query.getZbdlmy();
        if (!StringUtils.isEmpty(zbdlmy)) {
            qw.eq("zbdlmy", zbdlmy);
        }
        String zbdlid = query.getZbdlid();
        if (!StringUtils.isEmpty(zbdlid)) {
            qw.eq("zbdlid", zbdlid);
        }
        String spksfqy = query.getSpksfqy();
        if (!StringUtils.isEmpty(spksfqy)) {
            qw.eq("spksfqy", spksfqy);
        }
        String spkjfzs = query.getSpkjfzs();
        if (!StringUtils.isEmpty(spkjfzs)) {
            qw.eq("spkjfzs", spkjfzs);
        }
        // 1:直播中 2:预告 3:回放 4:停止
        List<LbsZbjl> lsit = lbsZbjlMapper.selectList(qw);
        if(lsit!=null) {
        	for (LbsZbjl lbz : lsit) {
        		String zbzt = lbz.getZbjzt();
        		if(zbzt!=null && ("101".equals(zbzt) || "102".equals(zbzt))) {
        			try {
        				// 101 直播中  102 未开始 103已结束
        				//1:直播中 2:预告 3:回放 4:停止
						GetActivityAPIResponse getActivityAPIResponse = liveVideoService.getActivityInfo(lbz.getId());
						int satat = getActivityAPIResponse.getResult().getStatus();
						boolean isUpate = false;
						String zbztUpate = zbzt;
						if(satat !=3) {
							if("101".equals(zbzt) && satat==4) {//发生了变化
								zbztUpate = "103";//已结束
								isUpate = true;
							}
							if("102".equals(zbzt) && (satat==1 || satat==4)) {//发生了变化
								if(satat==1) {
									zbztUpate = "101";//已结束
									isUpate = true;
								}else {
									zbztUpate = "103";//已结束
									isUpate = true;
								}
							}
						}
						if(isUpate) {
							lbz.setZbjzt(zbztUpate);
							LbsZbjl updateLbsZbjl = lbsZbjlMapper.selectById(lbz.getId());
							updateLbsZbjl.setZbjzt(zbztUpate);
							updateLbsZbjl.setUpdateTime(LocalDateTime.now());
							lbsZbjlMapper.updateById(updateLbsZbjl);
						}
						
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
        }
        return lsit;
    }

    /**
     * 新增直播列表
     *
     * @param lbsZbjl 直播列表
     * @return 结果
     */
    @Transactional
    public int insert(LbsZbjl lbsZbjl) {
        lbsZbjl.setDeptZbjId(SecurityUtils.getDeptZbjId());
        lbsZbjl.setZbjbmid(SecurityUtils.getDeptZbjId());
        lbsZbjl.setDelFlag(0);
        lbsZbjl.setCreateTime(LocalDateTime.now());
        DateTime dateTime =  DateUtil.parse(lbsZbjl.getJhkssj());
        long zbkssj = dateTime.getTime()/1000;
        try {
        	
        	String subUserName = sysConfigUtils.getSubUserName(SecurityUtils.getDeptZbjId());
        	if(StrUtil.isBlankIfStr(subUserName)) {
        		throw new RuntimeException("直播间子账户未配置正确，请联系管理员!");
        	}
        	LOG.error("创建直播间-直播间ID["+SecurityUtils.getDeptZbjId()+"], subUserName["+subUserName+"]");
        	
        	CreateActivityAPIResponse createActivityAPIResponse = liveVideoService.createActivity(lbsZbjl.getZbjmc(), subUserName, zbkssj, lbsZbjl.getSpfmt());
        	CommonResp result = createActivityAPIResponse.getResult();
        	ResponseMetadata responseMetadata = createActivityAPIResponse.getResponseMetadata();
        	com.volcengine.model.response.ResponseMetadata.Error error = responseMetadata.getError();
        	if(error!=null) {
    	        throw new RuntimeException("直播间创建失败，请重试code:"+error.getMessage()+" msg："+error.getMessage()+ "codeN" +error.getCodeN());
        	}else {
        		long id = result.getActivityId();
        		
        		//这里修改为可获取推流主备地址以及拉流主备地址
				GetStreamsAPILineDetail getStreamsAPILineDetail = liveVideoService.getStreamsInfo(id);
				
				if(null != getStreamsAPILineDetail ) {
					LOG.error("直播间创建完成 getStreamsAPILineDetail["+ JSONObject.toJSONString(getStreamsAPILineDetail)  +"]");
					//主推流地址
					PushInfoAPI mainPushInfo = getStreamsAPILineDetail.getMainPushInfo();
					lbsZbjl.setZbtldz(mainPushInfo.getPushPath());
					lbsZbjl.setZbtlmy(mainPushInfo.getStreamingCode());
					
					//备用推流地址
					PushInfoAPI backPushInfo = getStreamsAPILineDetail.getBackPushInfo();
					lbsZbjl.setZbtlbydz(backPushInfo.getPushPath());
					lbsZbjl.setZbtlbymy(backPushInfo.getStreamingCode());
					
					//主拉流地址
					ForwardInfoAPI mainForwardInfo = getStreamsAPILineDetail.getForwardInfo();
					lbsZbjl.setZblldz(mainForwardInfo.getPullStreamUrl());
					lbsZbjl.setZbllmy(mainForwardInfo.getPullStreamStatus());
					
					//备用拉流地址
					ForwardInfoAPI backForwardInfo = getStreamsAPILineDetail.getBackupForwardInfo();
					lbsZbjl.setZbllbydz(backForwardInfo.getPullStreamUrl());
					lbsZbjl.setZbllbymy(backForwardInfo.getPullStreamStatus());
					
				}
        		
            	String viewUrl = result.getViewUrl();
            	lbsZbjl.setId(id);
            	lbsZbjl.setViewurl(viewUrl);
            }
		} catch (Exception e) {
			e.printStackTrace();
	        throw new RuntimeException("直播间创建失败，请重试:"+e.getMessage());
		}
        
        try {
        	//设置敏感字
        	liveVideoService.addActivityAntidirtAPI(lbsZbjl.getId(), lbsMgzService.getMgs(lbsZbjl.getDeptZbjId()));
		} catch (Exception e) {
			e.printStackTrace();
		}
        return lbsZbjlMapper.insert(lbsZbjl);
    }

    /**
     * 修改直播列表
     *
     * @param lbsZbjl 直播列表
     * @return 结果
     */
    public int update(LbsZbjl lbsZbjl) {
        return lbsZbjlMapper.updateById(lbsZbjl);
    }

    /**
     * 批量删除直播列表
     *
     * @param ids 需要删除的直播列表主键
     * @return 结果
     */
    public int deleteByIds(Long[] ids) {
    	int num = 0;
    	try {
    		Long id = ids[0];
    		LbsZbjl lbsZbjl = lbsZbjlMapper.selectById(id);
    		if(lbsZbjl==null) {
    	        throw new RuntimeException("直播间不存在");
    		}
    		if(!"102".equals(lbsZbjl.getZbjzt())) {
    	        throw new RuntimeException("只有状态为未开始的才能删除！");
    		}
			CommonResponse commonResponse = liveVideoService.deleteActivity(id);
			ResponseMetadata responseMetadata = commonResponse.getResponseMetadata();
        	com.volcengine.model.response.ResponseMetadata.Error error = responseMetadata.getError();
        	if(error!=null) {
        		System.err.println(error.getCode());
            	System.err.println(error.getCodeN());
            	System.err.println(error.getMessage());
    	        throw new RuntimeException("直播间删除失败，请重试code:"+error.getMessage()+" msg："+error.getMessage()+ "codeN" +error.getCodeN());
        	}else {
        		Long[] delids = new Long[]{id};
    			num = lbsZbjlMapper.updateDelFlagByIds(delids);
        	}
		} catch (Exception e) {
			e.printStackTrace();
	        throw new RuntimeException("直播间删除失败，请重试:"+e.getMessage());
			
		}
        return num;
    }

    /**
     * 删除直播列表信息
     *
     * @param id 直播列表主键
     * @return 结果
     */
    public int deleteById(Long id) {
        Long[] ids = {id};
        return lbsZbjlMapper.updateDelFlagByIds(ids);
    }

	public int activityProductEnable(LbsZbjl lbsZbjl) {
		long zbjid = lbsZbjl.getId();
		LbsZbjl updateLbsZbjl = selectById(zbjid);
		if(updateLbsZbjl==null) {
	        throw new RuntimeException("操作失败，直播间信息不存在！请刷新重试");
		}
		String spksfqy = lbsZbjl.getSpksfqy();
		boolean sfkq = false;
		if("1".equals(spksfqy)) {
			sfkq = true;
		}
		try {
			ModifyActivityMenusResponse  mamr = productVideoService.activityProductEnable(zbjid, sfkq);
			com.volcengine.model.response.ResponseMetadata.Error error = mamr.getResponseMetadata().getError();
        	if(error!=null) {
        		System.err.println(error.getCode());
            	System.err.println(error.getCodeN());
            	System.err.println(error.getMessage());
    	        throw new RuntimeException("操作失败，请重试:code:"+error.getMessage()+" msg："+error.getMessage()+ "codeN" +error.getCodeN());
        	}else {
        		updateLbsZbjl.setSpksfqy(spksfqy);
    			return update(updateLbsZbjl);
        	}
		} catch (Exception e) {
			e.printStackTrace();
	        throw new RuntimeException("操作失败，请重试:"+e.getMessage());
		}
		
	}

	public LbsZbjl selectByPushInfoAPIId(Long id) {
		LbsZbjl lbsZbjl = lbsZbjlMapper.selectById(id);
		try {
			if(lbsZbjl!=null && lbsZbjl.getZbtldz()==null && lbsZbjl.getZbtlmy()==null) {
				
				//这里修改为可获取推流主备地址以及拉流主备地址
				GetStreamsAPILineDetail getStreamsAPILineDetail = liveVideoService.getStreamsInfo(id);
				
				if(null != getStreamsAPILineDetail ) {
					
					//主推流地址
					PushInfoAPI mainPushInfo = getStreamsAPILineDetail.getMainPushInfo();
					lbsZbjl.setZbtldz(mainPushInfo.getPushPath());
					lbsZbjl.setZbtlmy(mainPushInfo.getStreamingCode());
					
					//备用推流地址
					PushInfoAPI backPushInfo = getStreamsAPILineDetail.getBackPushInfo();
					lbsZbjl.setZbtlbydz(backPushInfo.getPushPath());
					lbsZbjl.setZbtlbymy(backPushInfo.getStreamingCode());
					
					//主拉流地址
					ForwardInfoAPI mainForwardInfo = getStreamsAPILineDetail.getForwardInfo();
					lbsZbjl.setZblldz(mainForwardInfo.getPullStreamUrl());
					lbsZbjl.setZbllmy(mainForwardInfo.getPullStreamStatus());
					
					//备用拉流地址
					ForwardInfoAPI backForwardInfo = getStreamsAPILineDetail.getBackupForwardInfo();
					lbsZbjl.setZbllbydz(backForwardInfo.getPullStreamUrl());
					lbsZbjl.setZbllbymy(backForwardInfo.getPullStreamStatus());
					
					
				}
				
				lbsZbjlMapper.updateById(lbsZbjl);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
        return lbsZbjl;
	}
	
	


	
}
